import { config } from '../config.js'

// 服务器错误码对应提示信息
const tips = {
  999: '抱歉，出现了一个错误',
  1005: 'appKey无效,请前往www.7yue.pro申请',
  3000: '期刊不存在'
}

class HTTP {

  request({url, data={}, method='GET'}) {
    return new Promise((resolve, reject) => {
      this._request(url, resolve, reject, data, method)
    })
  }

  _request(url, resolve, reject, data, method) {
    wx.request({
      url: config.apiBaseUrl + url,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json',
        'appKey': config.appKey
      },
      success: (res) => {
        let code = res.statusCode.toString()
        if (code.startsWith('2')) {
          resolve(res.data)
        } else {
          reject()
          this._showError(res.data.error_code)
        }
      },
      fail: (error) => {
        reject()
        this._showError()
      }
    })
  }
  /**
   * 显示错误信息
   */
  _showError(code = 999) {
    wx.showToast({
      title: tips[code],
      icon: 'none',
      duration: 2000
    })
  }
}

export { HTTP }